/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of the LMF library client Project nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 * Stephanie Stroka
 *
 * File Info:
 * User: Stephanie Stroka
 * Date: 2011/08/19
 * Time: 18:04
 *
 * Project: lmflib
 */

package kiwi.facading.utils;

import kiwi.facading.model.KiWiFacade;
import kiwi.facading.model.resources.KiWiNode;
import kiwi.facading.model.resources.KiWiResource;

import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

/**
 * @author Sebastian Schaffert
 *
 */
public class FacadeUtils {

	/**
	 * Check whether a type is a KiWi Facade, i.e. inherits from the KiWiFacade interface
	 *
	 * @param <C>
	 * @param clazz
	 * @return
	 */
	public static <C> boolean isKiWiFacade(Class<C> clazz) {
		if (KiWiFacade.class.isAssignableFrom(clazz)) {
			return true;
		} else {
			return false;
		}
	}

    /**
      * Check whether a type is a KiWi Node, i.e. inherits from the KiWiNode class
      *
      * @param <C>
      * @param clazz
      * @return
      */
     public static <C> boolean isKiWiNode(Class<C> clazz) {
         if (KiWiNode.class.isAssignableFrom(clazz)) {
             return true;
         } else {
             return false;
         }
     }

    /**
      * Check whether a type is a KiWi Node, i.e. inherits from the KiWiNode class
      *
      * @param <C>
      * @param clazz
      * @return
      */
     public static <C> boolean isKiWiResource(Class<C> clazz) {
         if (KiWiResource.class.isAssignableFrom(clazz)) {
             return true;
         } else {
             return false;
         }
     }


	/**
	 * Check whether a type is a KiWi Facade, i.e. the type or one of its superclasses has
	 * the @KiWiFacade annotation.
	 *
	 * @param <C>
	 * @param clazz
	 * @return
	 */
	public static <C> boolean isFacadeAnnotationPresent(Class<C> clazz, Class<? extends Annotation> annotation) {
		if (clazz.isAnnotationPresent(annotation)) {
			return true;
		} else {
			for(final Class iface : clazz.getInterfaces()) {
				if(iface.isAnnotationPresent(annotation)) {
					return true;
				}
			}
			if (clazz.getSuperclass() != null) {
				return isFacadeAnnotationPresent(clazz.getSuperclass(),annotation);
			}
			return false;
		}
	}


	public static <C extends Annotation,D> C getFacadeAnnotation(Class<D> clazz, Class<C> annotation) {
		if (clazz.isAnnotationPresent(annotation)) {
			return clazz.getAnnotation(annotation);
		} else {
			for(final Class iface : clazz.getInterfaces()) {
				if(iface.isAnnotationPresent(annotation)) {
					return (C) iface.getAnnotation(annotation);
				}
			}
			if (clazz.getSuperclass() != null) {
				return getFacadeAnnotation(clazz.getSuperclass(),annotation);
			}
			return null;
		}

	}


    /**
     * Returns true if the <code>clazz</code> argument is a
     * KiWiEntity, otherwise it returns false.
     *
     * @param in the argument to test.
     * @return true if the <code>clazz</code> argument is a KiWi
     *         entity.
     */
    public static boolean isKiWiFacade(Object in) {

        if (in == null) {
            return false;
        }

        final Class<?> clazz = in.getClass();
        final boolean result = isKiWiFacade(clazz);

        return result;
    }

    /**
     * Check whether a type is a collection (List, Set, ...).
     *
     * @param <C> the type of the class modeled by the
     *            <code>clazz</code> argument Class object. For
     *            example, the type of String.class is Class
     *            &lt;String&gt;
     * @param clazz the type to test.
     * @return true if the type to test is a a type is a
     *         collection (List, Set, ...).
     */
    public static <C> boolean isCollection(Class<C> clazz) {

        if (clazz == null) {
            return false;
        }

        final Class<?>[] interfaces = clazz.getInterfaces();

        if (Arrays.asList(interfaces).contains(Collection.class)) {
            return true;
        }

        if (clazz.getSuperclass() != null) {
            return isCollection(clazz.getSuperclass());
        }

        return false;
    }


    /**
     * Returns true if the <code>clazz</code> argument is a:
     * <ul>
     * <li>a primitive
     * <li>a primitive wrapper
     * <li>a java.lang.Localle class
     * <li>a java.lang.Date class
     * <li>a java.lang.String class
     * </ul>
     * otherwise it returns false.
     *
     * @param <C> the type of the class modeled by the
     *            <code>clazz</code> argument Class object. For
     *            example, the type of String.class is Class
     *            &lt;String&gt.
     * @param clazz the argument to test.
     * @return true if the <code>clazz</code> argument is a
     *         primitive, primitive wrapper, locale, date or
     *         String.
     */
    public static <C> boolean isBaseType(Class<C> clazz) {

        if (clazz == null) {
            return false;
        }

        final boolean isPrimitive = clazz.isPrimitive();
        if (isPrimitive) {
            return true;
        }

        // if I compare the Locale.class with the clazz argument
        // I can avoid the infamous case when the clazz is null,
        // the Locale.class.equals(null) is false, always - at
        // least this sustains the theory. The same logic for
        // the other equals realtions.
        final boolean isLocale = Locale.class.equals(clazz);
        if (isLocale) {
            return true;
        }

        final boolean isDate = Date.class.equals(clazz);
        if (isDate) {
            return true;
        }

        final boolean isString = String.class.equals(clazz);
        if (isString) {
            return true;
        }

        final boolean isBoolean = Boolean.class.equals(clazz);
        if (isBoolean) {
            return true;
        }

        final Class<? super C> superClass = clazz.getSuperclass();
        final boolean isNumber = Number.class.equals(superClass);
        if (isNumber) {
            return true;
        }

        // even if the char is a primitive is not a number
        final boolean isCharacter = Character.class.equals(clazz);
        if (isCharacter) {
            return true;
        }

        return false;
    }

    /**
     * Returns true if the <code>clazz</code> argument is a:
     * <ul>
     * <li>a primitive
     * <li>a primitive wrapper
     * </ul>
     * otherwise it returns false.
     *
     * @param <C> the type of the class modeled by the
     *            <code>clazz</code> argument Class object. For
     *            example, the type of String.class is Class
     *            &lt;String&gt.
     * @param clazz the argument to test.
     * @return true if the <code>clazz</code> argument is a
     *         primitive or primitive wrapper.
     */
    public static <C> boolean isPrimitive(Class<C> clazz) {

        if (clazz == null) {
            return false;
        }

        final boolean isPrimitive = clazz.isPrimitive();
        if (isPrimitive) {
            return true;
        }

        // even if the char is a primitive is not a number
        final boolean isCharacter = Character.class.equals(clazz);
        if (isCharacter) {
            return true;
        }

        final Class<? super C> superClass = clazz.getSuperclass();
        final boolean isNumber = Number.class.equals(superClass);
        if (isNumber) {
            return true;
        }

        return false;
    }

    /**
     * Returns true if the <code>in</code> argument is a:
     * <ul>
     * <li>a primitive
     * <li>a primitive wrapper
     * </ul>
     * otherwise it returns false.
     *
     * @param in the argument to test.
     * @return true if the <code>clazz</code> argument is a
     *         primitive or primitive wrapper.
     */
    public static boolean isPrimitive(Object in) {
        if (in == null) {
            return false;
        }

        final Class<?> clazz = in.getClass();
        return isPrimitive(clazz);
    }


	/**
	 * Transform a value passed as string to the base type (i.e. non-complex type) given as argument
	 *
	 * @param <T>
	 * @param value
	 * @param returnType
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static <T> T transformToBaseType(String value, Class<T> returnType) throws IllegalArgumentException {
		// transformation to appropriate primitive type
		if(Integer.class.equals(returnType) || int.class.equals(returnType)) {
			if(value == null) {
                return (T)(Integer)0;
            }
			return (T)(Integer)Integer.parseInt(value);
		} else if(Long.class.equals(returnType) || long.class.equals(returnType)) {
			if(value == null) {
                return (T)(Long)0L;
            }
			return (T)(Long)Long.parseLong(value);
		} else if(Double.class.equals(returnType) || double.class.equals(returnType)) {
			if(value == null) {
                return (T)(Double)0.0;
            }
			return (T)(Double)Double.parseDouble(value);
		} else if(Float.class.equals(returnType) || float.class.equals(returnType)) {
			if(value == null) {
                return (T)(Float)0.0F;
            }
			return(T)(Float)Float.parseFloat(value);
		} else if(Byte.class.equals(returnType) || byte.class.equals(returnType)) {
			if(value == null) {
                return (T)(Byte)(byte)0;
            }
			return (T)(Byte)Byte.parseByte(value);
		} else if(Boolean.class.equals(returnType) || boolean.class.equals(returnType)) {
			return (T)(Boolean)Boolean.parseBoolean(value);
		} else if(Character.class.equals(returnType) || char.class.equals(returnType)) {
			if(value == null) {
				return null;
			} else if(value.length() > 0) {
				return (T)(Character)value.charAt(0);
			} else {
				return null;
			}
		} else if (Locale.class.equals(returnType)) {
			if(value == null) {
				return null;
			} else {
				return (T) new Locale(value);
			}
		} else if (Date.class.equals(returnType)) {
			if(value == null) {
				return null;
			} else {
				try {
					return (T) KiWiFormatUtils.ISO8601FORMAT.parse(value);
				} catch (final ParseException e) {
					e.printStackTrace();
					return null;
				}
			}
		} else if(String.class.equals(returnType)) {
			return (T)value;
		} else {
			throw new IllegalArgumentException("primitive type "+returnType.getName()+" not supported by transformation");
		}
	}

	/**
	 * Transform a value passed as string to the base type (i.e. non-complex type) given as argument
	 *
	 * @param <T>
	 * @param value
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static <T> String transformFromBaseType(T value) throws IllegalArgumentException {
		// transformation to appropriate primitive type
		if(value == null) {
			return null;
		} else if(Integer.class.equals(value.getClass()) || int.class.equals(value.getClass())) {
			return value.toString();
		} else if(Long.class.equals(value.getClass()) || long.class.equals(value.getClass())) {
			return value.toString();
		} else if(Double.class.equals(value.getClass()) || double.class.equals(value.getClass())) {
			return value.toString();
		} else if(Float.class.equals(value.getClass()) || float.class.equals(value.getClass())) {
			return value.toString();
		} else if(Byte.class.equals(value.getClass()) || byte.class.equals(value.getClass())) {
			return value.toString();
		} else if(Boolean.class.equals(value.getClass()) || boolean.class.equals(value.getClass())) {
			return value.toString();
		} else if(Character.class.equals(value.getClass()) || char.class.equals(value.getClass())) {
			return value.toString();
		} else if (Locale.class.equals(value.getClass())) {
			return value.toString();
		} else if (Date.class.equals(value.getClass())) {
			return KiWiFormatUtils.ISO8601FORMAT.format(value);
		} else if(String.class.equals(value.getClass())) {
			return value.toString();
		} else {
			throw new IllegalArgumentException("primitive type "+value.getClass().getName()+" not supported by transformation");
		}
	}



}
